#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include "save_image.h"
#include "global.h"


void guess_image_file_name(int cam_num, char* file_name) 
{
	struct tm *tmv;
	time_t t;

	time(&t);
	tmv = localtime(&t);

	sprintf(file_name, "%d-%d-%d-%d-%d-%d-%d.ppm", tmv->tm_year+1900,
			tmv->tm_mon+1, tmv->tm_mday, tmv->tm_hour,
			tmv->tm_min, tmv->tm_sec, cam_num);

}
int save_image(unsigned char* buf, int cam_num) 
{
	int i;
	FILE* f;
	char file_name[512];
	unsigned char* p;

	guess_image_file_name(cam_num, file_name);

	f = fopen(file_name, "w");
	if (f == NULL) {
		fprintf(stderr, "%s: file could not be opend\n", file_name);
		return -1;
	}

	fprintf(f, "P3 # P3 Type\n");
	fprintf(f, "%d # Width is %d pixels\n", width, width);
	fprintf(f, "%d # Height is %d pixels\n", height, height);
	fprintf(f, "%d # True Color\n", 255);

	p = buf;
	for( i=0; i<width*height; i++) {
		fprintf(f, "%d %d %d ", *p, *(p+1), *(p+2));
		p=p+3;
		if((i%3)==0 && (i%15) !=0)
			fprintf(f, "\t");
		if(i%15 == 0)
			fprintf(f, "\n");
	}
	fclose(f);
	return 1;
}
